<?php
/*
 * @Descripttion: 同步政府接口
 * @version: v1
 * @Author: Terry
 * @Date: 2020-09-15 16:27:31
 * @LastEditors: Terry
 * @LastEditTime: 2024-07-29 12:28:20
 */

namespace app\video\extend\libs;

use Exception;
use libs\ALiOss;
use libs\Image;
use think\facade\Db;
use libs\File;


class AicameraServer
{
    /**
     * 设备告警
     */
    public function alert($data)
    {
        try {
            $headerMap = $data['headerMap'];
            $type = $headerMap['type'];

            $messageId = $headerMap['message-id'];
            $timestamp = $headerMap['timestamp'];

            $deviceId = $headerMap['device-sn'];
            $cameraData = DB::table('video_projectCamera')
                ->where([
                    'isDelete' => 0,
                    'number' => $deviceId,
                ])
                ->field(['uuid', 'projectCode'])
                ->find();
            if (!$cameraData) throw new Exception('摄像头不存在');
            $type = [
                'head' => [
                    'message' => '人員未佩戴安全帽',
                    'type' => 'head',
                ],
                'person' => [
                    'message' => '人員進入危險區域',
                    'type' => 'area',
                ],
                'clothes' => [
                    'message' => '人員未穿反光衣',
                    'type' => 'clothes',
                ],
            ];
            // 处理不同消息类型
            switch ($headerMap['type']) {
                case "0":
                    $path = "cache/aiAlert/" . date('Ymd');
                    if (!makeDir($path)) throw new Exception('文件创建失败');
                    $sdk = new Image($path);
                    $res = $sdk->base642image($data['alarm_img']);
                    $oss = new ALiOss($res);
                    $image = $oss->upload($res);
                    foreach ($data['extend']['label'] as $key => $value) {
                        $default = [
                            'messgae' => '其他預警',
                            'type' => 'other',
                        ];
                        if (isset($type[$value])) {
                            $default = $type[$value];
                        }
                        $newData = [
                            'image' => $image . '?x-oss-process=style/water',
                            'type' => $default['type'],
                            'message' => $default['message'],
                            'cameraUuid' => $cameraData['uuid'],
                            'projectCode' => $cameraData['projectCode'],
                            'alertTime' => date('Y-m-d H:i:s', (int)($timestamp / 1000)),
                            'messageId' => $messageId,
                            'uuid' => createUuid(),
                        ];
                        $res = $this->updateBaseData($newData);
                        if (!$res) {
                            // ..添加log，记录这次失败保存失败的数据
                        }
                    }
                    break;
                case "1":
                    $path = "cache/aiAlert/" . date('Ymd');
                    $sdk = new File($path);
                    $res = $sdk->binaryToFile($data['alarm_mp4'], 'mp4');
                    $oss = new ALIOss($res);
                    $video = $oss->upload($res);
                    // $video = 'https://auxface-oss-dev.oss-cn-hangzhou.aliyuncs.com/cache/aiAlert/20241208/1701_1733650973_201.mp4';
                    foreach ($data['extend']['label'] as $key => $value) {
                        $default = [
                            'messgae' => '其他預警',
                            'type' => 'other',
                        ];
                        if (isset($type[$value])) {
                            $default = $type[$value];
                        }
                        $newData = [
                            'video' => $video,
                            'type' => $default['type'],
                            'message' => $default['message'],
                            'cameraUuid' => $cameraData['uuid'],
                            'projectCode' => $cameraData['projectCode'],
                            'alertTime' => date('Y-m-d H:i:s', (int)($timestamp / 1000)),
                            'messageId' => $messageId,
                            'uuid' => createUuid(),
                        ];
                        $res = $this->updateBaseData($newData);
                        if (!$res) {
                            // ..添加log，记录这次失败保存失败的数据
                        }
                    }

                    break;
                case "2":
                    // ....上下线消息，业务逻辑处理....
                    break;
                default:
                    break;
            }
            // \think\facade\Log::info("返回的信息: " . json_encode($result));
            return result(200);
        } catch (\Throwable $th) {
            return result(FAIL, '', $th->getMessage());
        }
    }

    /**
     * 测速预警上传
     */
    public function speedCheck($data)
    {
        try {
            $fileName = $data['shotTime'] . '.jpg';
            request()->file('file')->move('upload/', '/' . $fileName);


            file_put_contents("send.txt", date('Y-m-d H:i:s'));
            file_put_contents("speedCheck.txt", json_encode($data));

            $info = DB::table('confinedspace_projectcamera')->where([
                ['equipment_No', '=', $data['equipment_No']]
            ])->find();
            if (!$info) throw new Exception('摄像头不存在');

            $exp = explode('.', $fileName);
            $oss = new ALIOss($exp[0], $exp[1]);
            $imageUrl = $oss->upload($fileName);

            $saveData = [
                'projectCode' => $info['projectCode'],
                'cameraUuid' => $info['uuid'],
                'shotTime' => $data['shotTime'],
                'plateColor' => $data['plateColor'],
                'vehicleColor' => $data['vehicleColor'],
                'vehicleType' => $data['vehicleType'],
                'spped' => $data['spped'],
                'imageUrl' => $imageUrl,
                'carNumber' => $info['carNumber'],
            ];
            $where = [
                'carNumber' => $data['carNumber'],
                'shotTime' => $data['shotTime'],
            ];
            $baseData = DB::table('video_carLog')->where($where)->value('uuid');
            if($baseData) {
                DB::table('video_carLog')->where($where)->update($saveData);
            }else{
                $saveData['uuid'] = createUuid();
                DB::table('video_carLog')->insert($saveData);
            }

            $return['result'] = [
                'uuid' => $saveData['uuid'],
            ];
            return result(200, $return, '');
        } catch (\Throwable $th) {
            return result(FAIL, '', $th->getMessage());
        }
    }

    /**
     * @Description: 更新数据库的书(增加或者修改)
     * @Author: Terry
     * @Date: 2024-12-08 16:14:20
     * @param {*} $data
     */
    private function updateBaseData($data)
    {
        $tableName = 'video_cameraAlert';
        $where = [
            'type' => $data['type'],
            'messageId' => $data['messageId'],
        ];
        $baseData = DB::table($tableName)->where($where)->value('uuid');
        if (!$baseData) $res = DB::table($tableName)->insert($data);
        else  $res = DB::table($tableName)->where($where)->update($data);
        return $res;
    }
}
